package com.example.jackson.controller;

import com.example.jackson.dto.UserDTO;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SerializationController {
    /**
     * 测试反序列化
     * @return
     * @throws Exception
     */
    @GetMapping("/user")
    public UserDTO getUser() throws Exception{
        String jsonStr = "{\"name\":\"lisi\",\"age\":12,\"addr\":\"linyi\"}";
        ObjectMapper objectMapper = objectMapper();
        return objectMapper.readValue(jsonStr, UserDTO.class);
    }

    /**
     * 测试序列化
     * @return
     * @throws Exception
     */
    @GetMapping("/userStr")
    public String getUserStr() throws Exception{
        UserDTO userDTO = new UserDTO();
        userDTO.setAge(12);
        userDTO.setName("lisi");
        ObjectMapper objectMapper = objectMapper();
        return objectMapper.writeValueAsString(userDTO);
    }

    /**
     * 测试ObjectNode
     * @return
     * @throws Exception
     */
    @GetMapping("/ObjectNode")
    public String testObjectNode() throws Exception{
        ObjectMapper objectMapper = objectMapper();
        ObjectNode node = objectMapper.createObjectNode();
        node.put("name", "zhangsan");
        node.put("age", 12);
        JsonNode name = node.get("name");
        String s = name.asText();
        JsonNode age = node.get("age");
        int i = age.asInt();
        long l = age.asLong();
        return "success";
    }

    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 关键配置：启用默认的类型信息，用于处理多态性
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, // 其它几个参数，试了有问题
                JsonTypeInfo.As.PROPERTY // 默认属性名是 @class
        );
        // 关键配置：忽略JSON中存在但目标类未定义的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return objectMapper;
    }
}
